package com.heima.admin.gateway.filter;

import com.heima.admin.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Order(1)  // 越小越优先
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.判断当前是否登录，登录则放行
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getURI().getPath();
        if (url.contains("/login/in")) {
            return chain.filter(exchange);
        }
        try {
            String token = request.getHeaders().getFirst("token");
            //2.1 token是否存在并且有效， 无效则拦截
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int verifyToken = AppJwtUtil.verifyToken(claims);
            if (StringUtils.isBlank(token) || verifyToken > 0) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            //2.2 token有效， 解析token jwt user id ， 存到 请求 header 中，下发到对应的微服务
            Integer id = claims.get("id", Integer.class);
            ServerHttpRequest httpRequest = request.mutate().headers(header -> {
                header.add("userId", id.toString());
            }).build();
            exchange.mutate().request(httpRequest).build();

        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("parse JWT is error：{}", ex);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        return chain.filter(exchange);
    }
}
